package com.runjian.rundo.iot.agent.common.network.tcp.client.handle;

import com.runjian.rundo.iot.agent.common.network.tcp.handle.AbstractDecoderMessageHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.ByteBufUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import lombok.extern.slf4j.Slf4j;

import java.util.List;

/**
 *
 * @author CaoQingHua
 */
@Slf4j
public class Iec104MessageDecoder extends AbstractDecoderMessageHandler {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> list) {
        if(log.isDebugEnabled()) {
            log.debug("待拆分字节:{}",ByteBufUtil.hexDump(in));
        }
        //读索索引
        int readIndex=in.readerIndex();
        //写入索引
        int writeIndex=in.writerIndex();
        //计数
        while (readIndex<writeIndex) {
            if(in.getByte(readIndex) == 0x68){
                //获取数值指定长度
                int length=(in.getByte(readIndex+1)& 0xff);
                //获取总数据长度
                int dataLength=length+2;
                if(readIndex+dataLength<=writeIndex){
                    ByteBuf ina=in.readBytes(dataLength);
                    list.add(ina);
                    readIndex+=dataLength;
                }else{
                    //长度不够了，跳出,等下一个侦路继续读取
                    break;
                }
            }else{
                //跳过这个字符
                in.skipBytes(1);
                readIndex++;
            }
        }
        if(log.isDebugEnabled()) {
            list.forEach(e->{
                log.debug("拆分后字节:{}",ByteBufUtil.hexDump((ByteBuf)e));
            });
        }
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //读取完成后,释放内存
        if(log.isDebugEnabled()){
            log.debug("该管道内存缓冲区都读取完成,释放内存!");
        }
        ctx.flush();
    }
}
